#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
from resource_management import *

class Slave(Script):

    def install(self, env):
        import params
        print('Starting Install the Slave of PGSQL ')
        #   安装
        version = params.pgsql_version
        data_dir = params.pgsql_data_dir
        Execute("yum remove postgresql* -y")
        # 安装客户端、服务端
        Execute('yum install postgresql{} -y'.format(version))
        Execute("yum install postgresql" + version + "-server -y")
        # 配置PGDATA
       
        Execute(
            "sed -i 's!^Environment=PGDATA.*!Environment=PGDATA={}!' /usr/lib/systemd/system/postgresql-{}.service".format(
                data_dir, version))
        Execute("systemctl daemon-reload")
        Execute("systemctl enable postgresql-" + version)
        print('Finish install the SLAVE of PGSQL')
        
        # 同步主数据库
        print('Starting sync master')
        master_host=default('/clusterHostInfo/postgresql_hosts',["localhost"])
        port = params.pgsql_server_port
        repuser_username = params.pgsql_db_repuser_username
        repuser_password = params.pgsql_db_repuser_password
        Execute("rm -rf {}".format(data_dir))
        Execute("mkdir -p {}".format(data_dir))
        Execute('su root -c "pg_basebackup -D {} -F p -X s -v -R -P -h {} -p {} -U {}"'.format(data_dir, master_host[0],port, repuser_username))

        Execute('chmod 700 {}'.format(data_dir))
        Execute('chown -R postgres:postgres {}'.format(data_dir))
            


    def configure(self, env):
        print("NO NEED TO CONFIG PGSQL SLAVE")
       

    def stop(self, env):
        import params
        version = params.pgsql_version
        print('Stop the PGSQL SLAVE ')
        Execute("systemctl stop postgresql-{}".format(version))

    def start(self, env):
        import params
        version = params.pgsql_version
        print('Start the PGSQL SLAVE')
        Execute("systemctl start postgresql-{}".format(version))

    def status(self, env):
        import params
        version = params.pgsql_version
        print('Status of the Slave of PGSQL')
        try:
            Execute("systemctl status postgresql-{}".format(version))
        except:
            print('PGSQL SLVAE IS NOT RUNNING')
            raise ComponentIsNotRunning()




if __name__ == "__main__":
    Slave().execute()